import React, { Component } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import './MapContainer.css';

interface AMapProps {
  value?: string;
  mapSearchCity?: string;
  mapStyle?: any;
  onChange?: (lnglat: string) => void;
  onCityChange?: (cityCode: string) => void;
}
interface AMapState {
  searchCity: string;
}

let map: any;
let autocomplete: any;
let placeSearch: any;
let geocoder: any;

class MapComponent extends Component<AMapProps, AMapState> {
  constructor(props: AMapProps) {
    super(props);
    this.state = {
      searchCity: props.mapSearchCity || '',
    };
  }
  // 2.dom渲染成功后进行map对象的创建
  componentDidMount() {
    const { value, mapSearchCity, onChange, onCityChange } = this.props;
    AMapLoader.load({
      key: '6978ee9e83dfe2655e8677454f43b697', //需要设置您申请的key
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'],
      AMapUI: {
        version: '1.1',
        plugins: [],
      },
      Loca: {
        version: '2.0.0',
      },
    })
      .then((AMap) => {
        map = new AMap.Map('mapcontainer', {
          resizeEnable: true,
          city: mapSearchCity,
          zooms: [2, 16],
          center: [117.942962, 28.455832],
        });
        map.addControl(new AMap.ToolBar());
        //搜索
        const autoOptions = {
          // 使用联想输入的input的id
          input: 'map_input',
          city: mapSearchCity,
        };
        autocomplete = new AMap.AutoComplete(autoOptions);
        placeSearch = new AMap.PlaceSearch({
          map: map,
          pageSize: 5, // 单页显示结果条数
          pageIndex: 1, // 页码
          panel: 'panel', // 结果列表将在此容器中进行展示。
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });

        autocomplete.on('select', function (e) {
          //TODO 针对选中的poi实现自己的功能
          placeSearch.setCity(e.poi.adcode);
          placeSearch.search(e.poi.name);
        });
        placeSearch.on('markerClick', function (e) {
          //e.data.adcode
          map.clearMap();
          const lnglat = e.event.lnglat;
          const m1 = new AMap.Marker({
            position: lnglat,
            animation: 'AMAP_ANIMATION_DROP',
          });
          map.add(m1);
          map.setFitView();
          if (onChange) {
            onChange(JSON.stringify(lnglat))
          }
          if (onCityChange) {
            onCityChange(e.data.adcode)
          }
        });
        //地址经纬度转换
        geocoder = new AMap.Geocoder();
        //点击地图添加标记
        map.on('click', function (ev) {
          map.clearMap();
          // 触发事件的对象
          // var target = ev.target;
          // 触发事件的地理坐标，AMap.LngLat 类型
          const lnglat = ev.lnglat;
          const m1 = new AMap.Marker({
            position: lnglat,
            animation: 'AMAP_ANIMATION_DROP',
          });
          map.add(m1);
          map.setFitView();
          if (onChange) {
            onChange(JSON.stringify(lnglat));
          }
          geocoder.getAddress(ev.lnglat, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              //result.regeocode.addressComponent.adcode
              if (onCityChange) {
                onCityChange(result.regeocode.addressComponent.adcode)
              }
            }
          })
        });
        if (value) {
          const m_d = new AMap.Marker({
            position: JSON.parse(value),//new AMap.LngLat(JSON.parse(value)),
            animation: 'AMAP_ANIMATION_DROP',
          });
          map.add(m_d);
          map.setFitView();
        }
      })
      .catch((e) => {
        // console.log(e);
      });
  }

  static getDerivedStateFromProps(props, current_state) {
    if (props.mapSearchCity !== current_state.searchCity) {
      autocomplete.setCity(props.mapSearchCity);
      return {
        searchCity: props.mapSearchCity,
      };
    }
    return null;
  }

  componentWillUnmount() {
    map.destroy();
  }

  render() {
    const { mapStyle } = this.props;

    return (
      <div className="home_div">
        <div id="mapcontainer" className="map" style={mapStyle} />
        <div id="myPageTop" className="myPageTop">
          <div>
            <div>请输入关键字：</div>
            <div>
              <input id="map_input" />
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default MapComponent;
